package just.stuff.morsels.objects;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;

import com.sleepycat.persist.model.DeleteAction;
import com.sleepycat.persist.model.Entity;
import com.sleepycat.persist.model.PrimaryKey;
import com.sleepycat.persist.model.Relationship;
import com.sleepycat.persist.model.SecondaryKey;

@Entity(version=1)
public class Morsel implements Serializable, Comparable<Morsel> {

	public static final String ROOT_ID = "";
	
	@PrimaryKey
	private String id;
	private String title;
	private String text;
	@SecondaryKey(relate=Relationship.MANY_TO_MANY, relatedEntity=Label.class, onRelatedEntityDelete=DeleteAction.ABORT)
	private Set<String> labels;
	@SecondaryKey(relate=Relationship.MANY_TO_ONE )
	private int relevance;
	@SecondaryKey(relate=Relationship.MANY_TO_ONE )
	private Date lastSaved;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public Set<String> getLabels() {
		return labels;
	}
	public void setLabels(Set<String> labels) {
		this.labels = labels;
	}
	public int getRelevance() {
		return relevance;
	}
	public void setRelevance(int relevance) {
		this.relevance = relevance;
	}
	public Date getLastSaved() {
		return lastSaved;
	}
	public void setLastSaved(Date lastSaved) {
		this.lastSaved = lastSaved;
	}
	
	public boolean isRoot() {
		return ROOT_ID.equals( id );
	}
	
	public int compareTo(Morsel o) {
		if( id != null && id.equals( o.id ) )
			return 0;
		int ret = relevance - o.relevance;
		if( ret == 0 ) {
			ret = lastSaved.compareTo( o.lastSaved );
			if( ret == 0 ) {
				ret = id != null ? id.compareTo( o.id ) : -1; //TODO: fix null case
			}
		}
		return -ret; //descending order
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Morsel other = (Morsel) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
	
	@Override
	public String toString() {
		return "Morsel [id=" + id + ", title=" + title + "]";
	}
	
	
	
	
}
